package deibay.server.backend.clients;

import java.io.Serializable;
import java.util.Date;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Vector;
import java.util.logging.Level;

import deibay.DeibayLogger;
import deibay.server.backend.ServerManager;
import deibay.server.eventargs.RemoveSessionEventArg;
import deibay.server.events.RemoveSessionEvent;
import deibay.util.IClosable;

public class VerifyClientsConnection implements Runnable, IClosable{

		private Hashtable<String, Session> sessions = null;
		private boolean keepAlive;
		private int waitSeconds; 		

		public VerifyClientsConnection(Hashtable<String, Session> sessions)
		{
			keepAlive = true;
			this.sessions = sessions;
			waitSeconds = 30;
		}
		
		public synchronized void run() {	

			synchronized(sessions)
			{
				while (sessions.isEmpty())
				{
					//System.err.println("OLAAA activity");
					try {
						sessions.wait();
					} catch (InterruptedException e) {
						DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Excepcao ao lancar o wait na thread ClientSessionActivity. \n");
					}
				}
			}

			while(keepAlive == true)
			{				
				Vector<Session> toRemove = new Vector<Session>();
				synchronized(sessions)
				{
					Date now = new Date(System.currentTimeMillis());			
					LinkedList<Session> sessionCollect = new LinkedList<Session>(sessions.values());
					for(Session s: (LinkedList<Session>) sessionCollect.clone())
					{				
						if(now.getTime() > s.getLastActivity().getTime()+(90*1000))
						{			
							DeibayLogger.getInstance().getLog().log(Level.WARNING, "Sessao do utilizador "+s.getUsername()+" esta sem actividade e sera removida.\n");
							toRemove.add(s);
						}					
					}
				}

				for (Session session : toRemove) {
					ServerManager.getInstance().getEventManager().fireEvent(new RemoveSessionEvent(new RemoveSessionEventArg(session.getUser())));
				}

				try {
					Thread.sleep(waitSeconds*1000);
				} catch (InterruptedException e) {				
					e.printStackTrace();
				}
			}

		}

		public void close() {
			keepAlive = false;			
		}
		
		public void restart()
		{
			try {
				Thread.sleep(20000);
				keepAlive = true;
				new Thread(this).start();		
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
}

	